package netudp;
/**
 * 组播
 */

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.util.Scanner;

public class M {

	public static void main(String[] args) {
		try {

			MulticastSocket ms = new MulticastSocket(9988);// 创建多播套接字
			InetAddress group = InetAddress.getByName("228.5.6.7");// 定义主播地址
			ms.joinGroup(group);// 主播套接字加入组地址
			new Thread() {
				byte[] buf = new byte[1024];
				DatagramPacket in = new DatagramPacket(buf, 1024);

				public void run() {
					while (true) {
						try {
							ms.receive(in);
							String mess = new String(in.getData(), 0, in.getLength());
							String usr = in.getAddress().getHostAddress();
							System.out.println(usr + "说" + mess);

						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}
			}.start();
			Scanner scan = new Scanner(System.in);
			byte[] buf = new byte[1024];// 创建数据包
			DatagramPacket out = new DatagramPacket(buf, 1024, group, 9988);
			String s;
			do {
				s = scan.nextLine();// 键盘输入
				out.setData(s.getBytes());// 给数据包设置数据
				ms.send(out);

			} while (!s.equals("bye"));
			ms.close();
			scan.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
